import logging

import pymongo
import pandas as pd
from pymongo.errors import BulkWriteError

import settings


class InitMultiCameraData:
    def __init__(self, excel_path):
        self.client = pymongo.MongoClient(settings.MONGO_MESSAGECENTER_CONNECT);
        self.db = self.client[settings.MONGO_MESSAGECENTER_DB_NAME];
        self.SHEET_LIST = ['device_position_info'];
        # 仓库数据
        pd_data = pd.read_excel(excel_path, sheet_name=self.SHEET_LIST[0], index_col=None, keep_default_na=False);
        self.documents = pd_data.to_dict(orient='records');

    def update_excel_location(self):
        collection = self.db[settings.MONGO_MESSAGECENTER_TABLE_LOCATION_ENTITY];
        bulk = pymongo.bulk.BulkOperationBuilder(collection, ordered=False);
        error_list = list();

        for index, data in enumerate(self.documents):
            try:
                # 根据 warehouse_id location_no 更新cameraIds
                warehouse_id = data['WarehouseId'];
                location_no = data['LocationNo'];
                if warehouse_id != '(null)' and location_no != '(null)':
                    # bulk.find({"warehouse_id": warehouse_id, "location_no": location_no}).upsert().update_one({'$append': {'cameraIds': data['videoId']}});
                    # bulk.find({"warehouse_id": warehouse_id, "location_no": location_no}).update({'$append': {'cameraIds': data['videoId']}});
                    # bulk.find({"warehouseId": warehouse_id, "locationNo": str(location_no)}).update({'$push': {'cameraIds': data['videoId']}});
                    bulk.find({"warehouseId": warehouse_id, "locationNo": str(location_no)}).update({'$addToSet': {'cameraIds': data['videoId']}});
                else:
                    print('摄像头未关联仓位 %s' % data);
                    # logging.debug("摄像头未关联仓位 {0}".format(data));

            except Exception as e:
                error_msg = '处理第 %s 条数据发生异常：%s 需要手动处理！异常数据：%s' % (index + 1, e, data);
                print(error_msg);
                error_list.append(error_msg);
                pass
            continue

        # 执行
        # try:
        result = bulk.execute();
        print('仓位信息modify_count>>%s' % (result.get("nModified")));
        if error_list:
            print('以下数据处理异常，需要手工矫正：');
            for error in error_list:
                print(error);
        # except BulkWriteError as bwe:
        #     logging.error(bwe);

    def update_excel_video(self):
        collection = self.db[settings.MONGO_MESSAGECENTER_TABLE_VIDEO_ENTITY];
        bulk = pymongo.bulk.BulkOperationBuilder(collection, ordered=False);
        error_list = list();

        for index, data in enumerate(self.documents):
            try:
                # 根据 videoId 更新cameraType 和 cameraName brand 通过接口同步
                video_id = data['videoId'];
                camera_type = data['cameraType'];
                camera_name = data['cameraName'];
                # bulk.find({"video_id": video_id, "location_no": location_no}).upsert().update_one({'$append': {'cameraIds': data['videoId']}});
                # bulk.find({"video_id": video_id, "location_no": location_no}).update({'$append': {'cameraIds': data['videoId']}});
                # bulk.find({"warehouseId": video_id, "locationNo": str(location_no)}).update({'$push': {'cameraIds': data['videoId']}});
                bulk.find({"videoId": video_id}).update({'$set': {'cameraType': camera_type,'cameraName':camera_name}});

            except Exception as e:
                error_msg = '处理第 %s 条数据发生异常：%s 需要手动处理！异常数据：%s' % (index + 1, e, data);
                print(error_msg);
                error_list.append(error_msg);
                pass
            continue

        # 执行
        # try:
        result = bulk.execute();
        print('摄像头信息modify_count>>%s' % (result.get("nModified")));
        if error_list:
            print('以下数据处理异常，需要手工矫正：');
            for error in error_list:
                print(error);
        # except BulkWriteError as bwe:
        #     logging.error(bwe);

    def update_excel_videoNVR(self):
        collection = self.db[settings.MONGO_MESSAGECENTER_TABLE_VIDEO_NVR_ENTITY];
        bulk = pymongo.bulk.BulkOperationBuilder(collection, ordered=False);
        error_list = list();

        for index, data in enumerate(self.documents):
            try:
                # 根据 videoId 更新cameraType 和 cameraName brand 通过接口同步
                nvr_id = data['nvrId'];
                nvr_brand = data['nvrBrand'];
                # bulk.find({"video_id": video_id, "location_no": location_no}).upsert().update_one({'$append': {'cameraIds': data['videoId']}});
                # bulk.find({"video_id": video_id, "location_no": location_no}).update({'$append': {'cameraIds': data['videoId']}});
                # bulk.find({"warehouseId": video_id, "locationNo": str(location_no)}).update({'$push': {'cameraIds': data['videoId']}});
                bulk.find({'_id': str(nvr_id)}).update({'$set': {'nvrBrand': nvr_brand}});

            except Exception as e:
                error_msg = '处理第 %s 条数据发生异常：%s 需要手动处理！异常数据：%s' % (index + 1, e, data);
                print(error_msg);
                error_list.append(error_msg);
                pass
            continue

        # 执行
        # try:
        result = bulk.execute();
        print('摄像头NVR信息modify_count>>%s' % (result.get("nModified")));
        if error_list:
            print('以下数据处理异常，需要手工矫正：');
            for error in error_list:
                print(error);
        # except BulkWriteError as bwe:
        #     logging.error(bwe);

if __name__ == '__main__':
    # 获取mongo连接
    # 读取excel数据
    handle = InitMultiCameraData(settings.EXCEL_INIT_MULTI_CAMERA_DATA);
    # 仓位更新数据
    handle.update_excel_location();
    # 读取摄像头更新数据
    handle.update_excel_video();
    # 读取nvr更新数据
    handle.update_excel_videoNVR();
